import { HTMLAttributes, memo, ReactNode } from "react";
import { LeftOutline } from "antd-mobile-icons";
import HeaderStyle from "./styled";
import { useNavigate } from "react-router-dom";
import { SearchBar } from "antd-mobile";
import { useDispatch } from "react-redux";
import { setSearchValue } from "../../states/home";
import { debounce } from "lodash-es";

interface IProps {
  title: string;
  showReturnBtn: boolean;
  returnClick?: (args?: any) => any;
  size: "small" | "big";
  showSearch?: boolean;
  slot_right?: ReactNode;
}

const Header = memo((props: IProps & HTMLAttributes<HTMLDivElement>) => {
  const {
    title,
    showReturnBtn,
    returnClick,
    size = "small" as "small" | "big",
    showSearch = false,
    className,
    slot_right
  } = props;
  const nav = useNavigate();
  const dispatch = useDispatch();

  const returnClickHandel = () => {
    if (returnClick) {
      returnClick();
      return;
    }
    nav(-1);
  };

  const searchHandel = debounce((value: string) => {
    dispatch(setSearchValue(value));
  }, 500) as (value: string) => void;

  return (
    <HeaderStyle size={size} className={className}>
      <div className="header">
        {showReturnBtn && (
          <div className="return" onClick={() => returnClickHandel()}>
            {<LeftOutline />}
          </div>
        )}
        <div className="title">{title}</div>
        <div className="slot_right">{slot_right}</div>
        {showSearch && (
          <div className="search">
            <SearchBar
              placeholder="搜索课程试试"
              onSearch={(value) => searchHandel(value)}
              onChange={(value) => searchHandel(value)}
            />
          </div>
        )}
      </div>
    </HeaderStyle>
  );
});

export default Header;
